<script setup>
import { ref } from "vue"
import { ElMessage, imageEmits } from 'element-plus'
import {useRouter,useRoute} from 'vue-router'
import { getCodeApi } from "@/api/user"
const route = useRoute()
const router = useRouter()
import {useUserStore} from '@/stores/user'
const userStore = useUserStore()
    //表单校验元素
    const loginForm = {
        username:'',
        password:''
    }
    const loginFormRef = ref(null)
    //校验规则
    const loginFormRules = {
    //用户名规则
    username:[
        {
            require:true,
            message:'用户名不能为空',
            trigger:'blur'
        },
        {
            min:6,
            max:20,
            message:'用户名长度在6-20之间',
            trigger:'blur'
        }
    ],
    //密码规则
    password:[
        {
            require:true,
            message:'密码不能为空',
            trigger:'blur'
        },
        {
            min:6,
            max:16,
            message:'密码长度在6-16之间',
            trigger:'blur'
        }
    ]
  }
  //登录请求
  const onLogin = ()=>{
      //整体校验
    loginFormRef.value.validate(async(valid)=>{
        if(!valid){
            ElMessage({
                message:'请检查输入内容',
                type:'error',
                plain:true
            })
            return
        }
        try{
            await userStore.loginAction(loginForm)
            router.push(route.query.redirectUrl || '/')
            
        }catch(e){
            ElMessage.error(e.response.data.msg)
            console.log(e)
        }
    })
  }
  //取消操作
  const onCancel = ()=>{
    loginFormRef.value.resetFields()
  }
 
 //强制刷新输入框视图 避免不能输入值
   function changeValue(e) {
        this.$forceUpdate()
    }
const loginType = ref(true)
const changeLoginType = ()=>{
    loginType.value = !loginType.value
}
//-------------------------------------------
//验证码登录
//表单校验元素
const codeLoginForm = {
    email:'',
    code:''
}

//登录
const onLoginByCode =async ()=>{
    if(codeLoginForm.code === '' || codeLoginForm.email === ''){
        ElMessage.warning('请检查参数！')
        return
    }
    try{
        console.log(codeLoginForm)
        await userStore.loginActionByCode(codeLoginForm)
        router.push(route.query.redirectUrl || '/')
    }catch(e){
        ElMessage.error('请求异常，请联系管理员')
        console.log(e)
    }
}
const onCancelByCode = ()=>{
    codeLoginForm.code = ''
    codeLoginForm.email = ''
}
//-------------------获取验证码----------
const showTime = ref(false)
const time = ref(Date.now()+ 1000 * 60 * 5)
const forbit = ref(false)
const getCode =async ()=>{
    if(codeLoginForm.email === ''){
        ElMessage.warning('请输入邮箱！')
        return
    }
    const inputEmail = codeLoginForm.email
    //校验邮箱格式是否正确
    const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (reg.test(inputEmail)){
        try{
            const resp = await getCodeApi(codeLoginForm.email)
            if(resp.data.code == 200){
                time.value = Date.now()+ 1000 * 60 * 5
                showTime.value = true
                forbit.value = true
                ElMessage.success('验证码已经发送注意查收！')
                return
            }
        }catch(e){
            console.log(e)
            ElMessage.error(e)
            return
        }
    }else {
        ElMessage.warning('邮箱格式不正确，请重新输入')
        return
    }
    
}

const reNew = async()=>{
    const time = ref(Date.now()+ 1000 * 60 * 5)
    forbit.value = false
    showTime.value = false
}
</script>

<template>
    <div class="login-box">
        <el-card>
            <template #header>
                <div class="card-header">
                    <h2 v-if="loginType">密码登录</h2>
                    <h2 v-else>验证码登录</h2>
                </div>
            </template>
            <!--账号密码登录 -->
            <el-form 
            v-if="loginType"
            ref="loginFormRef"
            :rules="loginFormRules"
            :model="loginForm">
                <el-form-item prop="username">
                    账号：
                    <el-input 
                    type="text"
                    v-model="loginForm.username"
                    @input="changeValue"
                    placeholder="请输入注册账号" 
                    clearable
                    prefix-icon="User" ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    密码：
                    <el-input 
                    v-model="loginForm.password"
                    type="password"
                    placeholder="请填写密码" 
                    @input="changeValue"
                    show-password
                    clearable
                    prefix-icon="Lock"></el-input>
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="onLogin">确认</el-button>
                    <el-button @click="onCancel">取消</el-button>
                    <br/>
                    <el-link
                    href="/register"
                   type="primary">
                   <el-icon><Promotion /></el-icon>
                   注册新用户</el-link>
                </el-form-item>
            </el-form>
            <!-- 验证码登录 -->
            <el-form 
            v-else
            :model="codeLoginForm">
                <el-form-item>
                    邮箱：
                    <el-input 
                    type="text"
                    v-model="codeLoginForm.email"
                    @input="changeValue"
                    placeholder="请输入邮箱" 
                    clearable
                    prefix-icon="User" ></el-input>
                </el-form-item>
                <el-form-item class="code-box" prop="password">
                验证码：
                    <el-input 
                    v-model="codeLoginForm.code"
                    type="text"
                    placeholder="请输入验证码" 
                    @input="changeValue"
                    clearable
                    prefix-icon="Lock">
                    </el-input>
                    <el-button
                      :disabled="forbit"
                      @click="getCode">获取验证码
                    </el-button>
                </el-form-item>
                <!-- 倒计时 -->
                <el-countdown
                  v-if="showTime"
                  @finish="reNew"
                  :value="time"
                  format="mm:ss"
                  suffix="秒后重新发送"/>
                <el-form-item>
                    <el-button type="primary" @click="onLoginByCode">登录</el-button>
                    <el-button @click="onCancelByCode">取消</el-button>
                    <br/>
                    <el-link
                    href="/register"
                   type="primary">
                   <el-icon><Promotion /></el-icon>
                   注册新用户</el-link>
                </el-form-item>
            </el-form>

            <el-button
            @click="changeLoginType "
            >切换登录方式</el-button>
        </el-card>
    </div>

</template>

<style lang="scss" scoped>
  .login-box{
    display: flex;
    justify-content: center;
    align-content: center; 
    background-image: linear-gradient(to right, #f2c4e5, #b2caf4);
    width: 100vw;
    height: 100vh;
    .el-card{
        .card-header{
            margin-top: -10px;
        }
        width: 40vw;
        height: 70vh;
        margin-top: 100px;
        :deep(.el-card__header){
            display: flex;
            align-content: center;
            justify-content: center;
            height: 60px;
            background: var( --el-color-primary) ;
            color: white;
            text-align: center;
            h2{
                font-size: 16px;
                font-weight: 400px;
            }
        }
        .el-form{  
            padding: 15px 25px;
            .el-form-item:nth-child(2){
                //上下外边距 40px 左右0
                 margin: 40px 0;
            }
            .el-form-item{
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
                flex-wrap: nowrap;
            }
            .el-input{
                height: 40px;
                width: 100%;
            }
            .el-button{
                height: 35px;
            }
            .code-box{
                .el-button{
                    color: #b2caf4;
                }
            }
        }

    }
  }  
</style>